package com.linsen.core.satoken.handler;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.ListUtil;
import com.linsen.core.common.model.User;
import com.linsen.core.common.util.ConvertUtil;
import com.linsen.core.satoken.constant.SaTokenConstant;
import lombok.RequiredArgsConstructor;

import java.util.List;

/**
 * @author zhaoyong
 * @date 2023/3/15
 */
@RequiredArgsConstructor
public class StpInterfaceHandler implements StpInterface {
    @Override
    public List<String> getPermissionList(Object o, String s) {
        SaSession saSession = StpUtil.getSessionByLoginId(o);
        Object data = saSession.get(SaTokenConstant.SESSION_PERMISSIONS_KEY, ListUtil.empty());
        return ConvertUtil.toList(data, String.class);
    }

    @Override
    public List<String> getRoleList(Object o, String s) {
        SaSession saSession = StpUtil.getSessionByLoginId(o);
        Object data = saSession.get(SaTokenConstant.SESSION_ROLES_KEY, ListUtil.empty());
        return ConvertUtil.toList(data, String.class);
    }

    public User getUser() {
        SaSession saSession = StpUtil.getSession();
        Object data = saSession.get(SaTokenConstant.SESSION_USER_KEY);
        return ConvertUtil.convert(data, User.class);
    }

    public User getUserByLoginId(String loginId) {
        SaSession saSession = StpUtil.getSessionByLoginId(loginId);
        Object data = saSession.get(SaTokenConstant.SESSION_USER_KEY);
        return ConvertUtil.convert(data, User.class);
    }

    public User getUserByTokenValue(String tokenValue) {
        SaSession saSession = StpUtil.getTokenSessionByToken(tokenValue);
        Object data = saSession.get(SaTokenConstant.SESSION_USER_KEY);
        return ConvertUtil.convert(data, User.class);
    }
}
